//
//  TreeNode.m
//  HelloWorld
//
//  Created by Beomjun Kim on 09. 08. 25.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "TreeNode.h"


@implementation TreeNode
@synthesize parent;
@synthesize children;
@synthesize key;
@synthesize leafvalue;

// Initialize all nodes as branches
- (TreeNode *) init
{
	if (self = [super init]) self.leafvalue = NULL;
	return self;
}

// Determine whether the node is a leaf or a branch
- (BOOL) isLeaf
{
	return (self.leafvalue != NULL);
}

// Return the first child that matches the key
- (TreeNode *) objectForKey: (NSString *) aKey
{
	for (TreeNode *node in self.children) 
		if ([[node key] isEqualToString: aKey]) return node;
	return NULL;
}

// Return the last child leaf value that matches the key
- (NSString *) leafForKey: (NSString *) aKey
{
	for (TreeNode *node in self.children) 
		if ([[node key] isEqualToString: aKey]) return node.leafvalue;
	return NULL;
}

// Print the tree to standard out
- (void) dumpAtIndent: (int) indent
{
	for (int i = 0; i < indent; i++) printf("--");
	
	printf("[%2d] Key: %s ", indent, [self.key UTF8String]);
	if (leafvalue) printf("(%s)", [self.leafvalue UTF8String]);
	printf("\n");
	
	for (TreeNode *node in self.children) [node dumpAtIndent:indent + 1];
}

- (void) dump
{
	[self dumpAtIndent:0];
}

- (void) dealloc
{
	NSLog(@"TreeNode dealloc");
	if (self.parent) [self.parent release];
	if (self.key) [self.key release];
	if (self.leafvalue) [self.leafvalue release];
	if (self.children) [self.children release];
	[super dealloc];
}

@end

